package com.tianyi.util;

import com.alibaba.fastjson.JSON;
import com.tianyi.model.SimpleLoginUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Objects;

/**
 * 加密工具
 *
 * @author cuixuhui
 * @date 2019/11/21
 */
public class EncryptUtil {

    private static Logger logger = LoggerFactory.getLogger(EncryptUtil.class);

    /**
     * 用户加密key
     */
    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";

    public static final String DES = "DES";
    public static final String AES = "AES";

    /**
     * 手机号加密key
     */
    public static final String PHONE_KEY = "TIANYI_PHONE_KEY";

    public static final String SYS_PWD_KEY = "TIANYI_SYS_USER_PWD_KEY";

    /**DES*/
    public static final int keysizeDES = 0;
    /**AES*/
    public static final int keysizeAES = 128;
    /**
     * 编码格式；默认使用uft-8
     */
    public static String charset = "utf-8";

    /**
     * 使用KeyGenerator双向加密，DES/AES，注意这里转化为字符串的时候是将2进制转为16进制格式的字符串，不是直接转，因为会出错
     * @param res 加密的原文
     * @param algorithm 加密使用的算法名称
     * @param key  加密的秘钥
     * @param keySize
     * @param isEncode
     * @return
     */
      private static final String keyGeneratorES(String res,String algorithm,String key,int keySize,boolean isEncode){
         try {
             KeyGenerator kg = KeyGenerator.getInstance(algorithm);
             if (keySize == 0) {
                 byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                 kg.init(new SecureRandom(keyBytes));
             }else if (key==null) {
                 kg.init(keySize);
             }else {
                 byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                 kg.init(keySize, new SecureRandom(keyBytes));
             }

             SecretKey sk = kg.generateKey();
             SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
             Cipher cipher = Cipher.getInstance(algorithm);
             if (isEncode) {
                 cipher.init(Cipher.ENCRYPT_MODE, sks);
                 byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
                 return parseByte2HexStr(cipher.doFinal(resBytes));
             }

             cipher.init(Cipher.DECRYPT_MODE, sks);
             return new String(cipher.doFinal(parseHexStr2Byte(res)));
         } catch (Exception e) {
             e.printStackTrace();
             logger.info("keyGeneratorES error {}", e.getMessage());
         }
         return null;
     }

    /**
     * 将二进制转换成16进制
     */
     public static String parseByte2HexStr(byte buf[]) {
         StringBuffer sb = new StringBuffer();
         for (int i = 0; i < buf.length; i++) {
                 String hex = Integer.toHexString(buf[i] & 0xFF);
                 if (hex.length() == 1) {
                         hex = '0' + hex;
                     }
                 sb.append(hex.toUpperCase());
             }
         return sb.toString();
     }
    /**
     * 将16进制转换为二进制
     */
     public static byte[] parseHexStr2Byte(String hexStr) {
         if (hexStr.length() < 1){
             return null;
         }
         byte[] result = new byte[hexStr.length()/2];
         for (int i = 0;i< hexStr.length()/2; i++) {
                 int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
                 int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
                 result[i] = (byte) (high * 16 + low);
             }
         return result;
     }

    /**
     * 使用DES加密算法进行加密（可逆）
     * @param res 需要加密的原文
     * @param key 秘钥
     * @return
     */
    public static String DESencode(String res, String key) {
        return keyGeneratorES(res, DES, key, keysizeDES, true);
    }
    /**
     * 对使用DES加密算法的密文进行解密（可逆）
     * @param res 需要解密的密文
     * @param key 秘钥
     * @return
     */
     public static String DESdecode(String res, String key) {
         return keyGeneratorES(res, DES, key, keysizeDES, false);
     }


    /**
     * 使用AES加密算法经行加密（可逆）
     * @param res 需要加密的密文
     * @param key 秘钥
     * @return
     */
     public static String AESencode(String res, String key) {
         return keyGeneratorES(res, AES, key, keysizeAES, true);
     }

     /**
       * 对使用AES加密算法的密文进行解密
       * @param res 需要解密的密文
       * @param key 秘钥
       * @return
       */
     public static String AESdecode(String res, String key) {

         return keyGeneratorES(res, AES, key, keysizeAES, false);
     }

    /**
     * 获取秘钥对象
     *
     * @param encryKey 加密key
     * @return
     * @throws Exception
     */
    private static final SecretKey getSecretKeyFactory(String encryKey) throws Exception {
        SecretKeyFactory des = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = des.generateSecret(new DESKeySpec(encryKey.getBytes()));
        return secretKey;
    }

    /**
     * 加密
     * @param param
     * @param encryKey 加密key
     * @return
     * @throws Exception
     */
    private static final String encryption(String param, String encryKey){
        try {
            Cipher cipher = Cipher.getInstance(DES);
            SecretKey secretKey = getSecretKeyFactory(encryKey);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return  new String(Base64.encodeBase64(cipher.doFinal(Objects.toString(param).getBytes())));
        }catch (Exception e){
            logger.info("encryption error {}, param={}, encryKey={}");
        }
        return null;
    }

    /**
     * 解密
     * @param value
     * @param encryKey 加密key
     * @return
     * @throws Exception
     */
    private static final String decrypt(String value, String encryKey){
        try {
            Cipher cipher = Cipher.getInstance(DES);
            SecretKey secretKey = getSecretKeyFactory(encryKey);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.decodeBase64(value.getBytes())));
        } catch (Exception e){

            logger.info("decrypt error {}, value={}, encryKey={}", e.getMessage(), value, encryKey);
        }
        return null;
    }

    /**
     * 登陆用户信息加密
     * @param loginUser
     * @return
     */
    public static String userEncryption(SimpleLoginUser loginUser) {

        String encryption = encryption(loginUser.toString(), LOGIN_USER_KEY);
        if (StringUtils.isBlank(encryption)){
            throw new RuntimeException("userEncryption encryption is blank");
        }
        logger.info("userEncryption loginUser={}, encryption={}", loginUser, encryption);
        return encryption;
    }

    /**
     * 登陆用户信息解密
     * @param userCode
     * @return
     */
    public static SimpleLoginUser userDecrypt(String userCode) {
        String sdecode = decrypt(userCode, LOGIN_USER_KEY);

        if (StringUtils.isBlank(sdecode)){
            throw new RuntimeException("userDecrypt error sdecode is blank");
        }
        SimpleLoginUser simpleLoginUser = JSON.parseObject(sdecode, SimpleLoginUser.class);
        logger.info("userDecrypt userCode={}, simpleLoginUser={}", userCode, simpleLoginUser);
        return simpleLoginUser;
    }

    /**
     * 手机号加密
     * @param phone
     * @return
     */
    public static String phoneEncrypt(Long phone){

        String phoneStr = Objects.toString(phone);
        String encryption = encryption(phoneStr, PHONE_KEY);
        if (StringUtils.isBlank(encryption)){
            throw new RuntimeException("phoneEncrypt error encryption is blank");
        }
        return encryption;
    }

    /**
     * 手机号解密
     * @param phone
     * @return
     */
    public static Long phoneDecrypt(String phone){

        String phoneStr = Objects.toString(phone);
        String encryption = decrypt(phoneStr, PHONE_KEY);
        if (StringUtils.isBlank(encryption)){
            throw new RuntimeException("phoneDecrypt encryption is blank");
        }
        return Long.valueOf(encryption);
    }

    /**
     * 加密
     * @param pwd
     * @return
     */
    public static String pwdEncrypt(String pwd){

        String pwdStr = Objects.toString(pwd);
        String encryption = encryption(pwdStr, SYS_PWD_KEY);
        if (StringUtils.isBlank(encryption)){
            throw new RuntimeException("pwdEncrypt error encryption is empty");
        }
        return encryption;
    }

    /**
     * 解密
     * @param pwd
     * @return
     */
    public static String pwdDecrypt(String pwd){

        String pwdStr = Objects.toString(pwd);
        String encryption = decrypt(pwdStr, SYS_PWD_KEY);
        if (StringUtils.isBlank(encryption)){
            throw new RuntimeException("pwdDecrypt error encryption is empty");
        }
        return encryption;
    }


}
